package chapter_24.tcp.upload;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;

/**
 * Created by Administrator
 * Created time 2018/8/10 13:32.
 * 案例:文件上传工具(客户端)
 */
public class UploadClient {

    public static void main(String[] args) {

        // 运行前先删除文件
        File file = new File("./src/chapter_24/tcp/upload/server.png");
        file.delete();

        System.out.println("客户端程序运行...");

        try (// 向本机的 6666 端口发出请求
             Socket socket = new Socket("127.0.0.1", 6666);
             // 由 Socket 获得输出流,并创建缓冲输出流
             BufferedOutputStream outputStream = new BufferedOutputStream(socket.getOutputStream());
             // 由文件输出流创建缓冲输出流
             FileInputStream inputStream = new FileInputStream("./src/chapter_24/tcp/upload/client.png");
             // 由文件输入流创建缓冲输入流
             BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        ) {
            // 缓冲区
            byte[] bytes = new byte[1024];
            // 首次从 Socket 读取数据
            int len = bufferedInputStream.read(bytes);

            while (len != -1) {
                // 写入 Socket
                outputStream.write(bytes, 0, len);
                // 再次从文件读取数据
                len = bufferedInputStream.read(bytes);
            }

            System.out.println("上传文件完成!");

        } catch (ConnectException e) {
            System.out.println("服务器未启动!");
        } catch (FileNotFoundException e) {
            System.out.println("文件未找到!");
        } catch (IOException e) {
            System.out.println("IOException");
        }

    }

}
